import { onHide, onShow } from '@dcloudio/uni-app'
import { onUnmounted, ref, watch } from 'vue'

/**
 * 下拉刷新
 * @param threshold: 下拉阈值
 */
export function refreshHandler(threshold: number = 500) {
  //窗口滚动的距离,置顶才可下拉刷新
  const rollDistance = ref(0)

  //加载时长定时器
  const timer = ref(0)

  //是否显示刷新窗口
  const isRefresh = ref(false)

  //刷新窗口向下移动的距离
  const moveBottom = ref(0)

  //用户第一次触摸时候的距离
  const startTouch = ref({
    clientX: 0,
    clientY: 0,
  })

  watch(
    () => isRefresh.value,
    (newValue, oldValue) => {
      if (newValue) {
        timer.value = setTimeout(() => {
          isRefresh.value = false
          moveBottom.value = 0
        }, 9000)
      } else {
        clearTimerHandler()
      }
    }
  )

  //监听用户开始下滑手势
  const startTouchendHandler = (e: any) => {
    //如果当前页面没有置顶
    if (rollDistance.value > 0) {
      return
    }
    startTouch.value.clientX = e.changedTouches[0].clientX
    startTouch.value.clientY = e.changedTouches[0].clientY
  }

  //监听用户松开下滑手势
  const endTouchendHandler = (e: any) => {
    //如果当前页面没有置顶 且并不处于刷新中
    if (rollDistance.value > 0 || isRefresh.value) {
      return
    }

    isRefresh.value =
      e.changedTouches[0].clientY - startTouch.value.clientY > threshold

    // 如果刷新状态已经结束
    if (!isRefresh.value) {
      moveBottom.value = 0
    }
  }

  /**
   * 刷新结束
   * @param time 可选·延迟关闭时间
   */
  const refreshEnd = (time: number = 0) => {
    setTimeout(() => {
      isRefresh.value = false
      moveBottom.value = 0
    }, time)
  }

  //监听用户滑动手势
  const moveTouchendHandler = (e: any) => {
    //如果当前页面没有置顶 且并不处于刷新中
    if (rollDistance.value > 0 || isRefresh.value) {
      return
    }
    moveBottom.value = e.changedTouches[0].clientY - startTouch.value.clientY
  }

  //清除定时器
  const clearTimerHandler = () => {
    if (timer.value) {
      clearTimeout(timer.value)
    }
    if (isRefresh.value) {
      isRefresh.value = false
    }
    moveBottom.value = 0
  }

  // 页面隐藏
  onHide(() => {
    clearTimerHandler()
  })

  return {
    isRefresh,
    moveBottom,
    rollDistance,
    endTouchendHandler,
    startTouchendHandler,
    moveTouchendHandler,
    refreshEnd,
  }
}
